package implementation.sort.QuickSort;


import anaydis.sort.SorterType;
import com.sun.istack.internal.NotNull;

import java.util.Comparator;
import java.util.List;

public class QuickSortMedianOfThree extends QuickSorter {

    public QuickSortMedianOfThree() {
        super(SorterType.QUICK_MED_OF_THREE);
    }

    public <T> void sort(@NotNull Comparator<T> tComparator, @NotNull List<T> ts) {
        sort(tComparator, ts, 0, ts.size() - 1);
    }

    private <T> void sort(Comparator<T> comparator, List<T> list, int start, int end) {
        if (end <= start) return;

        if(end-start > 2){
            getMedian(comparator, list, end);
        }
        int i = partition(comparator, list, start, end);
        sort(comparator, list, start, i - 1);
        sort(comparator, list, i, end);
    }

    private <T> void getMedian(Comparator<T> comparator, List<T> list, int end) {
        if (greater(comparator, list, end - 2, end - 1) && greater(comparator, list, end, end - 2) ||
                greater(comparator, list, end - 2, end) && greater(comparator, list, end - 1, end - 2)) {
            swap(list, end, end - 2);
        } else if (greater(comparator, list, end - 1, end) && greater(comparator, list, end - 2, end - 1) ||
                greater(comparator, list, end - 1, end - 2) && greater(comparator, list, end, end - 1)) {
            swap(list, end, end - 1);
        }
    }


}
